﻿using SC.GridManage.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SC.GirdManage.Repository
{
    // created by FuMingJun
    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        private readonly GMDbContext db;
        //注入上下文-构造函数
        public BaseRepository(GMDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<int> CreateAsync(T entity)
        {
            db.Set<T>().AddAsync(entity);   
            return db.SaveChangesAsync();
        }
        /// <summary>
        /// 根据ID查询并返回单个实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<T> GetModelAsync(long Id)
        {
            return await db.Set<T>().FindAsync(Id);
        }
        /// <summary>
        /// 返回IQueryable查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<IQueryable<T>> QueryAsync()
        {
            return await Task.FromResult(db.Set<T>());
        }
        /// <summary>
        ///  返回IQueryable查询-带条件
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public Task<IQueryable<T>> QueryAsync(Expression<Func<T, bool>> expression)
        {
            return  Task.FromResult(db.Set<T>().Where(expression));
        }

        /// <summary>
        /// 仓储实现-更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        public Task<int> UpdateAsync(T entity)
        {
             db.Set<T>().Update(entity);
            return db.SaveChangesAsync();
        }
    }
}
